package com.hilinos.common.common;

import com.hilinos.common.common.handler.ITokenHandler;
import com.hilinos.common.common.handler.RequestErrorHandler;
import com.hilinos.common.common.handler.RequestTokenHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 项目引入Spring-web才会加载该模块
 */
@EnableConfigurationProperties({
        HilinWebConfig.class
})
public class HilinWebAutoConfig implements WebMvcConfigurer {

    @Bean
    public RequestErrorHandler requestErrorHandler() {
        return new RequestErrorHandler();
    }

    @Autowired(required = false)
    private ITokenHandler iTokenHandler;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        WebMvcConfigurer.super.addInterceptors(registry);
        registry.addInterceptor(new RequestTokenHandler(iTokenHandler));
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        WebMvcConfigurer.super.addCorsMappings(registry);
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedMethods("GET", "POST", "OPTIONS")
                .allowedOriginPatterns("*")
                .exposedHeaders(HttpHeaders.SET_COOKIE)
                .maxAge(3600L);
    }

}
